package net.myspring.middle.validator;

import net.myspring.common.utils.ValidationUtils;
import net.myspring.middle.domain.Role;
import net.myspring.middle.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

/**
 * Created by liuj on 2016-08-29.
 */
@Component
public class RoleValidator implements Validator {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public boolean supports(Class<?> clazz) {
        return Role.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Role role = (Role) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "code", "error.code", "角色编码不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.name", "角色名称不能为空");
        Role checkRole = roleMapper.findByCode(role.getCode());
        if (checkRole != null && !checkRole.getId().equals(role.getId())) {
            errors.rejectValue("code", "error.code", "角色编码已存在");
        }
        checkRole = roleMapper.findByName(role.getName());
        if (checkRole != null && !checkRole.getId().equals(role.getId())) {
            errors.rejectValue("name", "error.name", "角色名称已存在");
        }
    }
}
